package com.sxl.ocr.ocronnx.service.impl;

import com.benjaminwan.ocrlibrary.OcrEngine;
import com.benjaminwan.ocrlibrary.OcrResult;
import com.sxl.ocr.ocronnx.exception.OCRException;
import com.sxl.ocr.ocronnx.service.OCRService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Path;

/**
 * description:
 * author: shenxiaolong
 * date: 2021/1/27  14:50
 */
@Slf4j
@Service
public class OCRServiceImpl implements OCRService {

    @Autowired
    private OcrEngine ocrEngine;

    @Value("${ocr.modelsDir}")
    private String modelsDir;

    @Override
    public OcrResultVo getOnnxOcrResult(File file, int imgResize) {

        String jniLibDir = System.getProperty("java.library.path");
        String imagePath = file.getAbsolutePath();
        long length = file.length();
        log.info("java.library.path={}", jniLibDir);
        log.info("modelsDir={}", modelsDir);
        log.info("imagePath={}", imagePath);
        if (length == 0) { throw new OCRException(1002, "文件不能为空"); }
        log.info("临时文件大小={}", length);
        OcrResult ocrResult = ocrEngine.detect(imagePath, imgResize);
        boolean delete = file.delete();
        log.info("删除临时文件：{}", delete);
        return mapStructResult(ocrResult);
    }

    @Override
    public OcrResultVo getOnnxOcrResult(Path path, int imgResize) {
        return getOnnxOcrResult(path.toFile(), imgResize);
    }

    @Override
    public String getNcnnOcrResult(FilePart filePart) {
        return "接口待开发";
    }


    private OcrResultVo mapStructResult(OcrResult ocrResult) {
        return OcrResultVo.builder()
                .textBlocks(ocrResult.getTextBlocks())
                .strRes(ocrResult.getStrRes())
                .detectTime(ocrResult.getDetectTime())
                .dbNetTime(ocrResult.getDbNetTime())
                .build();
    }

}
